#include<t_stdio.h>
#include<t_file.h>
#include <sys/types.h>      
#include <sys/socket.h>
#include <unistd.h>
#include <sys/time.h>
#include <string.h>
#include <sys/select.h>
#include<stdlib.h>
#include <arpa/inet.h>
#include<signal.h>
#define DBGPRINT printf

void sig_process(int signo){//信号处理函数
    printf("catch a exit signal..\n");
    _exit(0);
}

int main(int argc ,char * argv[]){
    int ret = -1;
    int  sock = -1;
    int  count;
    socklen_t from_len;
    struct sockaddr_in local_addr ; //本地地址
    struct sockaddr_in client_addr ; //客户端地址

    fd_set readfd ; //文件描述符集合,用于接收客户端请求
    char buffer[32];//设置数据数组，用于数据接收发送
    struct timeval timeout ;//超时设置
    timeout.tv_sec = 2;
    timeout.tv_usec = 0;

    signal(SIGINT,sig_process);//添加sigint信号到信号掩码
    //创建数据报套接字
    sock = socket(AF_INET , SOCK_DGRAM , 0);
    if(sock < 0) E_MSG("socket",-1);

    //本地地址数据清零
    //memset((void *)local_addr, 0 , sizeof(struct sockaddr_in));

    //设置本地地址数据
    local_addr.sin_family = AF_INET;
    local_addr.sin_addr.s_addr = htonl(INADDR_ANY);//本地地址
    local_addr.sin_port = htons(8888); //用8888端口进行监听
    //本地绑定
     ret = bind(sock , (struct sockaddr *)&local_addr, sizeof(local_addr));
    if(ret!=0)E_MSG("bind",-1);

    //主处理过程
    while(1){
        //先将文件描述符清零
        FD_ZERO(&readfd);
        //将套接字文件描述符加入读集合
        FD_SET(sock,&readfd);
        //监听是否有数据到来
         ret = select(sock+1 , &readfd , NULL,NULL,&timeout);
         printf("ret is : %d/n" , ret);
        switch (ret)
        {
        case -1 :
            //发生错误，
            break;
        case 0 :
        // 超时
            break;
        default: 
            //有数据到来
            if(FD_ISSET(sock , &readfd)){
                //接收数据
                from_len = sizeof(client_addr); // 初始化from_len
                count = recvfrom(sock , buffer , 32 , 0 ,(struct sockaddr *) & client_addr, from_len);
                DBGPRINT("recv msg is %s\n", buffer);//打印接收的信息
                if(strstr(buffer , "IP_FOUND")){//查看是否为ip广播请求数据报
                    //将应答数据复制进去
                    memcpy(buffer , "IP_FOUND_ACK" , strlen("IP_FOUND_ACK")+1);
                    //发送应答数据
                    count = sendto(sock , buffer , strlen(buffer) , 0 ,(struct sockaddr *)&client_addr,from_len);
                }
            }
      
        }

    }

    return 0;
}